<?php

namespace common\services;

use common\models\TallyArap;
use common\models\TallyFuture;
use common\models\TallyRecord;
use Yii;

class TallyStatReportServices extends BaseService
{
    public static function record_count_analysis($condition = []): array
    {
        $query = TallyRecord::find();

        if(isset($condition['tally_id'])){
            $query->andFilterWhere([
                '=','tally_id',$condition['tally_id']
            ]);
        }
        if(isset($condition['type'])){
            $query->andFilterWhere([
                '=','type',$condition['type']
            ]);
        }
        //如果有项目
        if(self::checkIsHasField($condition,'project_id')){
            $query->andFilterWhere([
                '=','project_id',$condition['project_id']
            ]);
        }

        if(isset($condition['store_id'])){
            $query->andFilterWhere([
                '=','store_id',$condition['store_id']
            ]);
        }

        if(isset($condition['account_id'])){
            $query->andFilterWhere([
                '=','account_id',$condition['account_id']
            ]);
        }

        // 时间段查询 包含右时间边界
        if($condition['begin_date'] != '' && $condition['end_date'] != '') {
            $condition['end_date'] = date('Y-m-d',strtotime('+1 day',strtotime($condition['end_date'])));
            $query->andFilterWhere(['between','tally_time',$condition['begin_date'], $condition['end_date']]);
        }
        $query->andFilterWhere([
            '<>','category_parent_id',0
        ]);
        $beQuewry = (clone $query);

        $countAmount = (clone $query)->sum('amount');
        if($countAmount == null){
            return [
                'amount'=>0,
                'results_list'=>[]
            ];
        }
        $resultDatas = [];

        if(self::checkIsHasField($condition,'groupRecordType')){
            if($condition['groupRecordType'] == '1'){
                $resultDatas = (clone $query)->groupBy('category_parent_id')
                    ->select('category_parent_id')->asArray()->all();

                foreach ($resultDatas as &$value){
                    $value['amounts'] = (clone $query)->andFilterWhere([
                        '=','category_parent_id',$value['category_parent_id']
                    ])->sum('amount');


                }
            }

            if($condition['groupRecordType'] == '2'){
                $resultDatas = (clone $query)->andFilterWhere([
                    '<>','category_child_id',0
                ])->groupBy('category_child_id')
                    ->select('category_child_id')
                    ->asArray()
                    ->all();
                foreach ($resultDatas as &$value){
                    $value['amounts'] = (clone $query)->andFilterWhere([
                        '=','category_child_id',$value['category_child_id']
                    ])->sum('amount');
                    $value['category_parent_id'] = $value['category_child_id'];
                }
            }
        }

        if(empty($resultDatas)){
            $resultDatas = $beQuewry->asArray()->all();

        }
        //根据分类id
        foreach ($resultDatas as &$value){
            $value['percent'] = (bcdiv($value['amounts'],$countAmount,4)*100).'%';
            if(self::checkIsHasField($condition,'groupRecordType')){
                if($condition['groupRecordType'] == '1'){
                    $value['category_parent_str'] = TallyCategoryService::getTitleGlobal($value['category_parent_id']);
                }

                if($condition['groupRecordType'] == '2'){
                    $value['category_parent_str'] = TallyCategoryService::getTitleGlobal($value['category_child_id']);
                }
                $value['project_name'] = '';
                if(self::checkIsHasField($condition,'project_id')){
                    $value['project_name'] = TallyProjectService::getTitleById($condition['project_id']);
                }
            }
        }


        return [
            'amount'=>$countAmount,
            'results_list'=>$resultDatas
        ];
    }




    public static function  count_debt_analysis($condition = []){
        $query =  TallyArap::find()->where([
            'tally_id' => $condition['tally_id']
        ]);
        if(self::checkIsHasField($condition,'project_id')){
            $query->andFilterWhere([
                '=','project_id',$condition['project_id']
            ]);
        }

        if($condition['begin_date'] != '' && $condition['end_date'] != '') {
            $condition['end_date'] = date('Y-m-d',strtotime('+1 day',strtotime($condition['end_date'])));
            $query->andFilterWhere(['between','tally_time',$condition['begin_date'], $condition['end_date']]);
        }


        $inRemainMoney = (clone $query)
            ->andFilterWhere(['=','type',TallyRecord::TYPE_IN])
            ->andFilterWhere(['>','state',TallyArap::STATE_INVALID])
            ->sum('amount_remain') ?? 0.00;

        // 全部状态下在已付金额
        $outRemainMoney = (clone $query)
            ->andFilterWhere(['=','type',TallyRecord::TYPE_OUT])
            ->andFilterWhere(['>','state',TallyArap::STATE_INVALID])
            ->sum('amount_remain') ?? 0.00;





        return [
            'inRemain' => $inRemainMoney,
            'outRemain' => $outRemainMoney,
            'debt'=>bcsub($inRemainMoney,$outRemainMoney,2)
        ];
    }

    public static function exportRecordList($export_type,$condition = [])
    {
        //收入

        $list = TallyRecordService::getAll($condition);

        $retData = [] ;
        foreach ($list as $lv) {
            if($lv['type'] == TallyRecord::TYPE_OUT) {
                $lv['amount'] = -1*$lv['amount'];
            }
            if($lv['type'] ==  TallyRecord::TYPE_TRANS) {
                $accountStr =  $lv['account_name'].'->'.$lv['account_dst_name'];
            }else{
                $accountStr = $lv['account_name'];
            }

            $one_category_name = $lv['category_ppname'] == '' ? $lv['category_pname'] : $lv['category_ppname'];
            $two_category_name = $lv['category_ppname'] == '' ? $lv['category_name'] : $lv['category_pname'];
            $three_category_name = $lv['category_ppname'] == '' ? '' : $lv['category_name'];

            $tmpData = [
                $lv['project_name'],
                substr($lv['tally_time'],0,10)."\t",//账单时间
                $one_category_name,
                $two_category_name,
                $three_category_name,
                $lv['amount'],
                $accountStr,
                $lv['store_name'],
                $lv['member_name'],
                $lv['memo'],
            ];
            $retData[] = $tmpData;
        }
        $filename = date('YmdHis').'-'.rand(1000,9999).'.csv';
        ToolService::downLoadCsv($filename,[
            '项目',
            '账单日期',
            '一级分类',
            '二级分类',
            '三级分类',
            '金额',
            '账户',
            '客户/供应商',
            '员工',
            '备注',
        ],$retData);
        return Yii::$app->request->hostInfo.'/index/down-export?file='.$filename;
    }

    public static function exportRecordAnalysis($export_type, $condition): string
    {

        $data = TallyStatReportServices::record_count_analysis($condition);
        $retData = [] ;
        foreach ($data['results_list'] as $lv){
            $one_category_name = TallyCategoryService::getTitleGlobal($lv['category_parent_id']);

            $tmpData = [
                $lv['project_name'],
                $lv['category_parent_str'],//账单时间
                $lv['amounts']."\t",
                ($lv['percent'])."%",
            ];
            $retData[] = $tmpData;
        }

        $filename = date('YmdHis').'-'.rand(1000,9999).'.csv';
        ToolService::downLoadCsv($filename,[
            '项目',
            '类别',
            '金额',
            '比例',
        ],$retData);
        return Yii::$app->request->hostInfo.'/index/down-export?file='.$filename;
    }

    public static function count_gua_anslysis($condition): array
    {

        $begin_date = '';
        if(isset($condition['begin_date'])){
            $begin_date = $condition['begin_date'];
            unset($condition['begin_date']);
        }
        $end_date = '';
        if(isset($condition['begin_date'])){
            $end_date = $condition['end_date'];
            unset($condition['end_date']);
        }

        //预先预付
        $fQuery = TallyFutureServices::getQuery(null,$condition)->andFilterWhere([
            '>','state',TallyFuture::STATE_INVALID
        ]);
        $fQuery->groupBy('type');
        $fQuery->select('sum(amount) as amounts,type,(sum(amount)-sum(amount_remain)) as leiji,sum(amount_remain) as wamounts');
        $fData = $fQuery->asArray()->all();



        //预先预付

        //应收应付
        $query = TallyArapService::getQuery(null,$condition)->andFilterWhere([
            '>','state',TallyArap::STATE_INVALID
        ]);
        $query->groupBy('type');
        $query->select('sum(amount) as amounts,type,(sum(amount)-sum(amount_remain)) as leiji,sum(amount_remain) as wamounts');
        $data = $query->asArray()->all();
        //应收应付

        $jichu_data = [
            '应收款'=>['amounts'=>0.00,'leiji'=>0.00,'wamounts'=>0.00,'type'=>10,'mamounts'=>0.00,'type_str'=>'应收款','type_str_text'=>0],
            '应付款'=>['amounts'=>0.00,'leiji'=>0.00,'wamounts'=>0.00,'type'=>20,'mamounts'=>0.00,'type_str'=>'应付款','type_str_text'=>0]
        ];

        foreach ($data as $value){
            if($begin_date != ''){
                $condition['begin_date'] = $begin_date;
            }
            if($end_date != ''){
                $condition['end_date'] = $end_date;
            }
            $condition['type'] = $value['type'];
            $value['mamounts'] = TallyRecordService::getQuery(null,$condition)->andFilterWhere([
                '<>','arap_id',0
            ])->sum('amount') ?? 0.00;
            $value['type_str'] = $value['type'] == 10 ? '应收款' :'应付款';
            $value['type_str_text'] = 0;
            $jichu_data[$value['type_str']] = $value;
        }
        $jichu_data_fu = [
            '预收款'=>['amounts'=>0.00,'leiji'=>0.00,'wamounts'=>0.00,'type'=>10,'mamounts'=>0.00,'type_str'=>'预收款','type_str_text'=>1],
            '预付款'=>['amounts'=>0.00,'leiji'=>0.00,'wamounts'=>0.00,'type'=>20,'mamounts'=>0.00,'type_str'=>'预付款','type_str_text'=>1]
        ];

        foreach ($fData as &$value){
            if($begin_date != ''){
                $condition['begin_date'] = $begin_date;
            }
            if($end_date != ''){
                $condition['end_date'] = $end_date;
            }
            $condition['type'] = $value['type'];
            $value['mamounts'] = TallyRecordService::getQuery(null,$condition)->andFilterWhere([
                '<>','future_id',0
            ])->andFilterWhere([
                '=','is_refund',0
            ])->sum('amount') ?? 0.00;
            $value['type_str'] = $value['type'] == 10 ? '预收款' :'预付款';
            $value['type_str_text'] = 1;
            $jichu_data[$value['type_str']] = $value;
        }
        return array_values(array_merge($jichu_data_fu,$jichu_data));
    }

    public static function gua_count_debt_rean($condition): array
    {
        $fQuery = TallyArapService::getQuery(null,$condition);

        if(!self::checkIsHasField($condition,'state')){
            $fQuery->andFilterWhere([
                '>','state',TallyFuture::STATE_INVALID
            ]);
        }




        return [
            'money_show'=>$fQuery->sum('amount'),
            'money_show1'=>$fQuery->sum('amount')-$fQuery->sum('amount_remain'),
            'money_show2'=>$fQuery->sum('amount_remain')
        ];

    }

    public static function future_count_debt_rean($condition)
    {
        $fQuery = TallyFutureServices::getQuery(null,$condition);

        if(!self::checkIsHasField($condition,'state')){
            $fQuery->andFilterWhere([
                '>','state',TallyFuture::STATE_INVALID
            ]);
        }




        return [
            'money_show'=>$fQuery->sum('amount'),
            'money_show1'=>$fQuery->sum('amount')-$fQuery->sum('amount_remain'),
            'money_show2'=>$fQuery->sum('amount_remain')
        ];
    }

    public static function exportArapList( $condition)
    {
        $list = TallyArapService::getAll($condition);
        $retData = [] ;
        foreach ($list as $lv) {
            $one_category_name = $lv['category_ppname'] == '' ? $lv['category_pname'] : $lv['category_ppname'];
            $two_category_name = $lv['category_ppname'] == '' ? $lv['category_name'] : $lv['category_pname'];
            $three_category_name = $lv['category_ppname'] == '' ? '' : $lv['category_name'];
            $monthAmount = TallyRecordService::getSumAmount($condition,$lv['id']);
            $tmpData = [
                ($lv['type'] == 10 ? '应收':'应付'),
                $lv['project_name'],
                substr($lv['tally_time'],0,10)."\t",//账单时间
                $one_category_name,
                $two_category_name,
                $three_category_name,
                TallyArap::getStatusTxt($lv['state']),
                $lv['amount'],
                bcsub($monthAmount,0,2),
                bcsub($lv['amount'],$lv['amount_remain'],2),
                $lv['amount_remain'],
                $lv['store_name'],
                $lv['member_name'],
                $lv['memo']
            ];
            $retData[] = $tmpData;
        }
        $filename = date('YmdHis').'-'.rand(1000,9999).'.csv';

        ToolService::downLoadCsv($filename,[
            '类型',
            '项目',
            '账单日期',
            '一级分类',
            '二级分类',
            '三级分类',
            '账单状态',
            '总金额',
            '累计核销金额',
            '当月核销金额',
            '未核销金额',
            '客户/供应商',
            '员工',
            '备注'
        ],$retData);
        return Yii::$app->request->hostInfo.'/index/down-export?file='.$filename;
    }

    public static function exportFutureAnalysis($condition)
    {
        $list = TallyFutureServices::getAll($condition);
        $retData = [] ;
        foreach ($list as $lv) {
            $one_category_name = $lv['category_ppname'] == '' ? $lv['category_pname'] : $lv['category_ppname'];
            $two_category_name = $lv['category_ppname'] == '' ? $lv['category_name'] : $lv['category_pname'];
            $three_category_name = $lv['category_ppname'] == '' ? '' : $lv['category_name'];
            $monthAmount = TallyRecordService::getSumAmountFuture($condition,$lv['id']);
            $tmpData = [
                ($lv['type'] == 10 ? '预收':'预付'),
                $lv['project_name'],
                substr($lv['tally_time'],0,10)."\t",//账单时间
                $one_category_name,
                $two_category_name,
                $three_category_name,
                TallyArap::getStatusTxt($lv['state']),
                $lv['amount'],
                bcsub($monthAmount,0,2),
                bcsub($lv['amount'],$lv['amount_remain'],2),
                $lv['amount_remain'],
                $lv['store_name'],
                $lv['member_name'],
                $lv['memo']
            ];
            $retData[] = $tmpData;
        }
        $filename = date('YmdHis').'-'.rand(1000,9999).'.csv';

        ToolService::downLoadCsv($filename,[
            '类型',
            '项目',
            '账单日期',
            '一级分类',
            '二级分类',
            '三级分类',
            '账单状态',
            '总金额',
            '累计核销金额',
            '当月核销金额',
            '未核销金额',
            '客户/供应商',
            '员工',
            '备注'
        ],$retData);
        return Yii::$app->request->hostInfo.'/index/down-export?file='.$filename;
    }

    public static function exportArapAnalysis($condition,$type = 0)
    {
        unset($condition['type']);
        unset($condition['export_type']);
        $list = self::count_gua_anslysis($condition);
        $retData = [] ;
        foreach ($list as $lv) {
            if($lv['type_str_text'] != $type){
                continue;
            }
            $project_name = '';
            if(self::checkIsHasField($condition,'project_id')){
                $project_name = TallyProjectService::getTitleById($condition['project_id']);
            }
            $tmpData = [
                $project_name,
                $type == 0 ? ($lv['type'] == 10 ? '预收款':'预付款') : ($lv['type'] == 10 ? '应收款':'应付款'),
                $lv['amounts'],
                $lv['leiji'],
                $lv['mamounts'],
                $lv['wamounts'],
            ];
            $retData[] = $tmpData;
        }
        $filename = date('YmdHis').'-'.rand(1000,9999).'.csv';
        ToolService::downLoadCsv($filename,[
            '项目',
            '类型',
            '总金额',
            '累计核销金额',
            '当月核销额',
            '未核销金额',

        ],$retData);
        return Yii::$app->request->hostInfo.'/index/down-export?file='.$filename;
    }
}